package com.cxs.controller;

import com.cxs.dto.AddUserDTO;
import com.cxs.dto.UpdateUserDTO;
import com.cxs.dto.UserSearchDTO;
import com.cxs.enums.HospitalErrorResultEnum;
import com.cxs.exception.HospitalException;
import com.cxs.pojo.User;
import com.cxs.service.UserService;
import com.cxs.vo.Result;
import com.cxs.vo.UserRoleVO;
import com.cxs.vo.UserSearchVO;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/10/18  10:11
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 系统管理-用户管理-显示所有用户
     *
     * @param searchDTO
     * @param pageNo
     * @param limit
     * @return
     */
    @GetMapping("/selectAllUser")
    public Result selectAllUser(UserSearchDTO searchDTO,
                                @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
        PageInfo<User> userPageInfo = userService.findUserBySearch(searchDTO, pageNo, limit);

        List<UserSearchVO> list = new ArrayList<>();

        for (User user : userPageInfo.getList()) {
            UserSearchVO searchVO = new UserSearchVO();
            BeanUtils.copyProperties(user, searchVO);
            searchVO.setPwd("");
            list.add(searchVO);
        }

        Result result = new Result();
        result.put("count", userPageInfo.getTotal());
        result.put("code", 0);
        result.put("msg", "");
        result.put("data", list);
        return result;
    }

    /**
     * 系统管理-用户管理-添加用户
     *
     * @param userDTO
     * @param bindingResult
     * @return
     */
    @PostMapping("/addUser")
    public Result addUser(@Valid AddUserDTO userDTO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.error(msg + "{}", userDTO);
            Result.failare(HospitalErrorResultEnum.USERNAME_PASSWORD_ERROR.getCode(), msg);
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userService.addUser(user);
        return Result.Ok("用户添加成功");
    }

    /**
     * 系统管理-用户管理-添加用户
     *
     * @param userDTO
     * @param bindingResult
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(@Valid UpdateUserDTO userDTO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.error(msg + "{}", userDTO);
            return Result.failare(HospitalErrorResultEnum.USER_UPDATE_USER_ERROR.getCode(), msg);
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userService.update(user);
        return Result.Ok("用户修改成功");
    }

    /**
     * 系统管理-用户管理-初始化角色信息
     *
     * @param userid
     * @return
     */
    @GetMapping("/initUserRole")
    public Result initUserRole(Integer userid) {

        if (StringUtils.isEmpty(userid) || userid <= 0) {
            log.error("【用户模块】:参数错误,userid = {}", userid);
            throw new HospitalException(HospitalErrorResultEnum.USER_PARAMETER_ERROR);
        }
        // 查询角色信息
        List<UserRoleVO> roleVOList = userService.getinitUserRoleInfo(userid);

        return Result.Ok(0, "", roleVOList);
    }

    /**
     * 系统管理-用户管理-分配角色
     *
     * @param userid 用户id
     * @param ids    角色id
     * @return
     */
    @PostMapping("/saveUserRole")
    public Result saveUserRole(Integer userid, Integer[] ids) {

        if (StringUtils.isEmpty(userid) || userid <= 0) {
            log.error("【用户分配角色】:用户id为空,userid = {}", userid);
            throw new HospitalException(HospitalErrorResultEnum.USER_PARAMETER_ERROR);
        }

        userService.updateUserRole(userid, Arrays.asList(ids));

        return Result.Ok("角色分配成功");
    }

    /**
     * 系统管理-用户管理-删除用户
     *
     * @param userId
     * @return
     */
    @GetMapping("/deleteUser/{id}")
    public Result deleteUser(@PathVariable("id") Integer userId) {
        if (StringUtils.isEmpty(userId) || userId <= 0) {
            log.error("【删除用户】:用户id为空,userid = {}", userId);
            throw new HospitalException(HospitalErrorResultEnum.USER_PARAMETER_ERROR);
        }

        userService.delete(userId);

        return Result.Ok("用户删除成功");
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @GetMapping("/resetUserPwd/{id}")
    public Result resetUserPwd(@PathVariable("id") Integer userId) {
        if (StringUtils.isEmpty(userId) || userId <= 0) {
            log.error("【密码重置】:用户id为空,userid = {}", userId);
            throw new HospitalException(HospitalErrorResultEnum.USER_PARAMETER_ERROR);
        }

        userService.initPwd(userId);

        return Result.Ok("密码重置成功");
    }
}
